package com.old.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.old.dto.PostLikeDTO;
import com.old.entity.Post;
import com.old.result.Result;
import com.old.service.HistoryService;
import com.old.service.PostService;
import com.old.service.impl.Recommendationservice;
import com.old.util.JwtUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/home")
@RequiredArgsConstructor
public class PostController {

    private final PostService postService;
    private final HistoryService historyService;

    private final Recommendationservice recommendationService;

    /**
     * 分页获取帖子列表（支持搜索和排序）
     */
    @GetMapping("/postList")
    public Result getPostList(@RequestParam(defaultValue = "1") Integer pageNo,
                              @RequestParam(defaultValue = "5") Integer pageSize,
                              @RequestParam (required = false)Integer sortBy,
                              @RequestParam (required = false)Integer userId,
                              @RequestParam (required = false)String searchTerms) throws JsonProcessingException {

//        PageBean pageList = postService.pageList(pageNo, pageSize, sortBy, searchTerms,userId);
//        log.info("分页查询: 页码={} 页大小={} 搜索词={} 排序方式={} 总数={}", pageNo, pageSize, searchTerms, sortBy, pageList.getTotal());
//        return Result.success(pageList);
        log.info("userId列表为:{}",userId);

        return Result.success(
                recommendationService.getRecommendedPosts(pageNo,pageSize, sortBy,searchTerms,userId)
        );

    }



    /**
     * 发布新帖子
     * @param post 帖子数据
     * @return 创建的帖子信息
     */
    @PostMapping("/addPost")
    public Result createPost(@RequestBody Post post) {
        Post createdPost = postService.createPost(post);
        log.info("发布新帖子成功，帖子ID: {}", createdPost.getId());
        return Result.success(createdPost);
    }


    /**
     * 获取帖子详情
     * @param id 帖子ID
     * @return 帖子详情
     */
    @GetMapping("/postInfo")
    public Result getPostDetail(@RequestParam Integer id ,
                                @RequestParam(required = false) Integer userId,
                                @RequestHeader(value = "Authorization") String token
    ) throws JsonProcessingException {

        //TODO 把从token获取改为从线程获取
        if(userId == null){
            userId = JwtUtil.getUserIdFromToken(token);
        }

        if (userId != null) {
            //保存浏览记录
            historyService.savePostHistory(userId, id);
        }

        Post post = postService.getPostDetail(id);
        log.info("获取帖子详情成功，帖子ID: {}", id);
    //    post.setIsgood(false);
        //查询用户是否点赞
        if (userId != null) {
            //传入userid
            boolean isGood = postService.isGood(userId, id);
            post.setIsgood(isGood);
        }else {
            //没传userid
            post.setIsgood(false);
        }
        return Result.success(post);
    }
    //点赞

    @PutMapping("/like")
    public Result <Map<String,Integer>> likePost(@RequestBody PostLikeDTO postLikeDTO){
        Integer likeCount=postService.likePost(postLikeDTO.getPostId(),postLikeDTO.getUserId());
        Map<String,Integer>response=new HashMap<>();
        response.put("like",likeCount);
        return Result.success(response);
    }


    //取消点赞

    @PutMapping("/noLike")
    public Result<Map<String, Integer>> cancelLike(@RequestBody PostLikeDTO likeDTO) {
        Integer likeCount = postService.cancelLike(likeDTO.getPostId(), likeDTO.getUserId());
        Map<String, Integer> response = new HashMap<>();
        response.put("like", likeCount);
        return Result.success(response);
    }

}
